// 为了方便，绕过services
const asyncBusboy = require('async-busboy');
const fs = require('fs');
const path = require('path');
const { passwordIsValid } = require('../lib/utilx');
const db = require('../model/index');
const User = db.models.User;
const BrowsePrivileges = db.models.BrowsePrivileges;
const Department = db.models.Department;
const Message = db.models.Message;
const extraAsideConfig = require('../../../config/extraAsideConfig');

class UserController {

  async login(ctx) {
    const {username, password} = ctx.request.body;
    let user = await User.findOne({
      where: {
        username,
        isStop: false,  // 没有被停用
      }
    });
    if(user) {
      if(passwordIsValid(password, user.salt, user.password)) {
        ctx.body = {
          code: 0,
          msg: {
            token: user.salt,
          }
        };
        return;
      }
    }
    ctx.body = {
      code: 1,
      msg: {
        error: '用户或密码错误',
      }
    }
  }

  async personalData(ctx) {
    let token = ctx.request.headers['token'];
    let user = await User.findOne({
      where: {
        salt: token,
      },
      attributes: {
        exclude: ['salt', 'password',]
      },
      include: [{
        model: Department,
        as: 'Department',
        include: [{
          model: BrowsePrivileges,
        }]
      }]
    });
    if(user) {
      ctx.body = {
        code: 0,
        msg: {
          user: {
            id: user.id,
            username: user.username,
            phone: user.phone,
            email: user.email,
            avatar: user.avatar,
            GroupId: user.Department && user.Department.id,
            extraAsideConfig: extraAsideConfig,
            groupname: user.Department && user.Department.name,
            browsePrivileges: user.Department.BrowsePrivilege,
          }
        }
      }
    } else {  // token不合法
      ctx.body = {
        code: -1,
        msg: {
          error: 'token无效',
        },
      }
    }
  }

  async fileUpload(ctx) {
    try{

      const { files } = await asyncBusboy(ctx.req);
      let file = files[0];
      let filename = `${new Date().getTime()}-${file.filename}`;
      let fr = fs.createWriteStream(path.join(__dirname, '../../files/', filename));
      file.pipe(fr);
      fr.on('finish', () => {
        // todo: 将文件属性修改为已上传
      });

      ctx.body = {
        code: 0,
        msg: {
          filename
        }
      };

    } catch(err) {
      console.log(err);
      ctx.body = {
        code: 0,
        msg: {
          url: '',
        }
      }
    }

  }

  async changeUserInfo(ctx){
    const { id, username, password, avatar, email, phone, realFileName } = ctx.request.body;
    console.log(id, avatar);
    if( id !== ctx.user.id ) {  // 非本用户
      ctx.body = {
        code: 100,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }

    if( username !== ctx.user.username ) {  // 如果是修改用户名
      let sameNameUser = await User.findOne({
        where: {
          username,
        }
      });
      if(sameNameUser) {
        ctx.body = {
          code: 6,
          msg: {
            error: '用户名已存在',
          }
        };
        return;
      }
    }

    await User.update({
      username,
      password: password || undefined,
      email,
      avatar,
      phone,
    }, {
      where: {
        id,
      }
    });

    ctx.body = {
      code: 0,
      msg: {}
    };
  }

  async getMessage(ctx) {
    const user = ctx.user;
    let messages = await Message.findAll({
      where: {
        UserId: user.id,
      }
    });
    ctx.body = {
      code: 0,
      msg: {
        totalCount: messages.length,
        messages,
      }
    }
  }

  async deleteMessage(ctx) {
    let { id } = ctx.request.body;
    await Message.destroy({
      where: {
        id,
      }
    });

    ctx.body = {
      code: 0,
      msg: {}
    }
  }
}

module.exports = new UserController();
